package com.lxz.bookmanager.controller.user;

import com.lxz.bookmanager.entity.Borrow;
import com.lxz.bookmanager.entity.Reader;
import com.lxz.bookmanager.mapper.BookMapper;
import com.lxz.bookmanager.entity.Book;
import com.lxz.bookmanager.service.BookService;
import com.lxz.bookmanager.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/user/book")
public class UserBookController {
    @Autowired
    private BookService bookService;

    @Autowired
    private BorrowService borrowService;

    @RequestMapping("/getAll")
    public String getAll(Model model) {
        List<Book> books = bookService.getAllBook();
        model.addAttribute("books", books);
        return "user/books";
    }

    @RequestMapping("/info/{id}")
    public String info(Model model, @PathVariable("id") String id) {
        Book book = bookService.getBookById(id);
        int count = bookService.selectBookCount(id);
        if (count > 0) {
            book.setState(1);
        }
        model.addAttribute("book", book);
        return "user/book_info";
    }

    //申请借阅图书
    @RequestMapping("/borrow/{id}")
    public String borrow(HttpSession session, Model model, @PathVariable("id") String id, Borrow borrow) {
        Book book = bookService.getBookById(id);
        int sernumNumber= (int) (Math.random()*10000);
        borrow.setSernum(sernumNumber);
        borrow.setBookid(book.getBookId());
        borrow.setBookname(book.getName());
        borrow.setBorrowusername(borrowService.applyReaderName((String) session.getAttribute("username")));
        borrow.setBorrowreaderid(borrowService.applyReaderId((String) session.getAttribute("username")));
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd:hh:mm:ss");
        borrow.setBorrowdate(calendar.getTime());
        borrowService.applyBorrowBook(borrow);
        return "user/books";

    }

    @RequestMapping("/search")
    public String search(String keyword, Model model) {
        List<Book> books = bookService.searchBook(keyword);
        model.addAttribute("books", books);
        return "user/book_search_result";
    }
}
